//
//  ST_RecentCallsViewController.swift
//  btvideo
//
// 最近通话记录
//
//  Created by mac on 2021/9/9.
//  Copyright © 2021 JarvanZhang. All rights reserved.
//

import UIKit
import MJRefresh
import RxSwift

class ST_RecentCallsViewController: UIViewController {

    /// 列表
    lazy var collectionView: UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        layout.scrollDirection = .vertical
        layout.itemSize = CGSize(width: UIScreen.main.bounds.width, height: 78)
        layout.minimumLineSpacing = 0
        let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
        collectionView.mj_header = MJRefreshNormalHeader(refreshingBlock: viewModel.refresh_data)
        collectionView.mj_footer = MJRefreshAutoNormalFooter(refreshingBlock: viewModel.load_more_data)
        collectionView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 49 + 10 + BTSafeAreaBottom, right: 0)
        collectionView.scrollIndicatorInsets = UIEdgeInsets(top: 0, left: 0, bottom: 49, right: 0)
        collectionView.backgroundColor = .white
        collectionView.register(cellWithClass: ST_RecentCallsItem.self)
        collectionView.dataSource = self
        collectionView.emptyDataSetSource = self
        collectionView.emptyDataSetDelegate = self
        
        return collectionView
    }()
    
    let viewModel = ST_RecentCallsViewModel()
    var disposeBag = DisposeBag()
    
    fileprivate var first = true
    
    override func viewDidLoad() {
        super.viewDidLoad()

        setup_views()
        bindRx()
        
    }
    
    @available(iOS 11.0, *)
    override func viewSafeAreaInsetsDidChange() {
        super.viewSafeAreaInsetsDidChange()
        
        collectionView.contentInset = UIEdgeInsets(top: 0 , left: 0, bottom: 49 + view.safeAreaInsets.bottom, right: 0)
        collectionView.scrollIndicatorInsets = UIEdgeInsets(top: 0, left: 0, bottom: 49 + view.safeAreaInsets.bottom, right: 0)
    }

    func setup_views() {
        
        if #available(iOS 11.0, *) {
            collectionView.contentInsetAdjustmentBehavior = .never
        } else {
            automaticallyAdjustsScrollViewInsets = false
        }
        
        view.addSubview(collectionView)
        collectionView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
    }

    func bindRx() {
        
        viewModel.onError
            .subscribe(onNext: { [weak self] error in
                self?.toast(text: error.localizedDescription)
            })
            .disposed(by: disposeBag)
        
        viewModel.onRefreshed
            .subscribe(onNext: { [weak self] isMoreDataExists in
                self?.collectionView.mj_header?.endRefreshing()
                if isMoreDataExists {
                    self?.collectionView.mj_footer?.resetNoMoreData()
                } else {
                    self?.collectionView.mj_footer?.endRefreshingWithNoMoreData()
                }
            })
            .disposed(by: disposeBag)
        
        viewModel.onMoreLoaded
            .subscribe(onNext: { [weak self] isMoreDataExists in
                if isMoreDataExists {
                    self?.collectionView.mj_footer?.endRefreshing()
                } else {
                    self?.collectionView.mj_footer?.endRefreshingWithNoMoreData()
                }
            })
            .disposed(by: disposeBag)
        
        viewModel.recentCalls
            .subscribe(onNext: { [weak self] recentCalls in
                self?.collectionView.mj_footer?.isHidden = recentCalls.count == 0
                self?.collectionView.reloadData()
            })
            .disposed(by: disposeBag)
        
        
        
        collectionView.rx.itemSelected.subscribe(onNext: {[weak self]  indexPath in
            
            guard let model = self?.viewModel.recentCalls.value[safe: indexPath.row] else{
                return
            }
            
            let vc = ST_PairsCenterViewController()
            
            vc.accid = model.targetAccid
            
            let nav = PairsCenterInteractiveNavigationController.init(rootViewController: vc)
            
            nav.overCurrentContext = true
            
            GlobalPresent(toController: nav)
            
        })
        .disposed(by: disposeBag)
        

        
        
        viewModel.refresh_data()
         
        
        viewModel.recentCalls.accept([])
        
    }
        
}

extension ST_RecentCallsViewController: UICollectionViewDataSource {
    
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        1
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        viewModel.recentCalls.value.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withClass: ST_RecentCallsItem.self, for: indexPath)
        let model = viewModel.recentCalls.value[indexPath.item]
        cell.configure(for: model)
        cell.operation_button.rx.tap
            .subscribe(onNext: { [weak self] in
                switch model.resourceType {
                case 1:
                    
                    
                    if ST_BTUserInfoManager.shared.confined_to_ticket(){
                        
                        let vc = ST_TicketViewController()
                        
                        vc.from = .mainIndexConfined
                        
                        GlobalPresent(toController: vc)
                        
                        return
                    }
                    
                    self?.viewModel.recall(id: model.id)
                    
                    ST_MediaChatDispatcher.shared.request_audio_permission_with_execute {
                                        
                        ST_MediaChatDispatcher.shared.inviteChat(sessionId: model.targetAccid, isVideo: false)
                    }
                case 2:
                    
                    self?.viewModel.recall(id: model.id)
                    
                    ST_MediaChatDispatcher.shared.request_audio_permission_with_execute {
                                        
                        ST_MediaChatDispatcher.shared.request_video_permission_with_execute {
                            
                            ST_MediaChatDispatcher.shared.inviteChat(sessionId: model.targetAccid, isVideo: true)
                        }
                    }
                default:
                    break
                }
            })
            .disposed(by: cell.disposeBag)
        return cell
    }
}



extension ST_RecentCallsViewController:DZNEmptyDataSetSource,DZNEmptyDataSetDelegate{
    
    func emptyDataSetShouldAllowScroll(_ scrollView: UIScrollView!) -> Bool {
        return true
    }
    
    func emptyDataSetShouldDisplay(_ scrollView: UIScrollView!) -> Bool {
        
        if first{
            self.first = false
            return false
        }else{
            return true
        }
    }
    
    func title(forEmptyDataSet scrollView: UIScrollView!) -> NSAttributedString! {
        
        let attrString = NSMutableAttributedString(string: "当前没有通话哦\n晚点再来看看")
        
        let attr: [NSAttributedString.Key : Any] = [.font: UIFont.systemFont(ofSize: 16),.foregroundColor: UIColor(red: 0.67, green: 0.71, blue: 0.75, alpha: 1)]
        
        attrString.addAttributes(attr, range: NSRange(location: 0, length: attrString.length))
        
        return attrString
    }
    
    func image(forEmptyDataSet scrollView: UIScrollView!) -> UIImage! {
        
        return ST_ImageUtils.imageName("首页_img_活跃(空)")
    }
}
